import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_vehicle.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/models/auth_application_model.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

class BindApplyToMeController extends GetxController {
  // 申请列表
  RxList<AuthApplicationModel> applicationList = <AuthApplicationModel>[].obs;

  @override
  void onInit() {
    super.onInit();
  }

  onRefresh() {
    return ApiHelper()
        .getSecondaryOwnerApplicationList(toMe: true)
        .then((list) {
      applicationList.clear();
      // 根据申请时间降序排列
      list.sort((a, b) => b.applyTime.compareTo(a.applyTime));
      applicationList.addAll(list);
    }).catchErrorHandler();
  }

  onLoadMore() async {}

  // 接受/拒绝授权申请
  handleApplicationOnTap(AuthApplicationModel application, bool accept) {
    if (application.id == null) {
      throw Exception("申请ID不能为空");
    }
    Loading.showLoading(null);
    ApiHelper()
        .handleSecondaryOwnerApplication(
            applyId: application.id!, accept: accept)
        .then((success) {
      // 重新刷新列表
      onRefresh();
      if (success) {
        Loading.showSuccess(accept
            ? local.vehicle_authorization_approved
            : local.vehicle_authorization_rejected);
      } else {
        Loading.showError(local.operation_failed);
      }
    }).catchErrorHandler();
  }
}
